package com.ropa.java;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadControll2 {
    public static void main(String[] args) {

        // forkjoinpool 使用了 work-stealing(工作窃取)算法
        // parallel stream 使用forkJoinpoll
        ExecutorService executorService = Executors.newWorkStealingPool();

        AtomicBoolean flag = new AtomicBoolean();
        TimeInterval timer = DateUtil.timer();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Thread currentThread = Thread.currentThread();
                    if (currentThread.isInterrupted()) {
                        System.err.println("线程被打断");
                    }
                    System.out.println("hello from pid" + currentThread.getName());
//                    try {
//                        Thread.sleep(2000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }

                    workTime(2000);
                }
            }
        });

        thread.start();


        for (int i = 0; i < 5; i++) {
            double totalTimeSeconds = timer.intervalSecond();
            System.out.println("totalTimeSeconds = " + totalTimeSeconds);
            if (totalTimeSeconds > 3 && thread.isAlive()) {
                thread.interrupt();
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private static void workTime(long ms) {
        final long l = System.currentTimeMillis();
        while (System.currentTimeMillis() <= l + ms) {
        }
    }
}


